// utils/cart.js
import { storageUtils } from './storage.js'

/**
 * 购物车管理工具
 * 提供购物车的增删改查功能
 */

class Cart {
  constructor() {
    this.items = []
    this.total = 0
    this.count = 0
    this.loadFromStorage()
  }

  /**
   * 从本地存储加载购物车数据
   */
  loadFromStorage() {
    try {
      const cartData = storageUtils.getCartData()
      if (cartData && Array.isArray(cartData)) {
        this.items = cartData
        this.updateTotals()
      }
    } catch (error) {
      console.error('加载购物车数据失败:', error)
    }
  }

  /**
   * 保存购物车数据到本地存储
   */
  saveToStorage() {
    try {
      storageUtils.setCartData(this.items)
      
      // 同步到全局数据
      const app = getApp()
      if (app && app.globalData) {
        app.globalData.cart = this.items
        app.globalData.cartTotal = this.total
      }
    } catch (error) {
      console.error('保存购物车数据失败:', error)
    }
  }

  /**
   * 添加商品到购物车
   * @param {Object} product 商品信息
   * @param {number} quantity 数量
   */
  addItem(product, quantity = 1) {
    if (!product || !product.id || quantity <= 0) {
      throw new Error('无效的商品信息或数量')
    }

    const existingItem = this.items.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += quantity
    } else {
      this.items.push({
        id: product.id,
        name: product.name,
        price: product.price,
        image: product.image,
        description: product.description,
        alcohol: product.alcohol,
        ibu: product.ibu,
        quantity: quantity,
        addTime: Date.now()
      })
    }

    this.updateTotals()
    this.saveToStorage()
    return this.items
  }

  /**
   * 移除购物车商品
   * @param {string} productId 商品ID
   */
  removeItem(productId) {
    const index = this.items.findIndex(item => item.id === productId)
    if (index > -1) {
      this.items.splice(index, 1)
      this.updateTotals()
      this.saveToStorage()
    }
    return this.items
  }

  /**
   * 更新商品数量
   * @param {string} productId 商品ID
   * @param {number} quantity 新数量
   */
  updateQuantity(productId, quantity) {
    if (quantity <= 0) {
      return this.removeItem(productId)
    }

    const item = this.items.find(item => item.id === productId)
    if (item) {
      item.quantity = quantity
      this.updateTotals()
      this.saveToStorage()
    }
    return this.items
  }

  /**
   * 增加商品数量
   * @param {string} productId 商品ID
   * @param {number} amount 增加数量
   */
  increaseQuantity(productId, amount = 1) {
    const item = this.items.find(item => item.id === productId)
    if (item) {
      item.quantity += amount
      this.updateTotals()
      this.saveToStorage()
    }
    return this.items
  }

  /**
   * 减少商品数量
   * @param {string} productId 商品ID
   * @param {number} amount 减少数量
   */
  decreaseQuantity(productId, amount = 1) {
    const item = this.items.find(item => item.id === productId)
    if (item) {
      const newQuantity = item.quantity - amount
      if (newQuantity <= 0) {
        return this.removeItem(productId)
      } else {
        item.quantity = newQuantity
        this.updateTotals()
        this.saveToStorage()
      }
    }
    return this.items
  }

  /**
   * 清空购物车
   */
  clear() {
    this.items = []
    this.total = 0
    this.count = 0
    this.saveToStorage()
    return this.items
  }

  /**
   * 获取购物车商品列表
   */
  getItems() {
    return this.items
  }

  /**
   * 获取购物车商品数量
   */
  getCount() {
    return this.count
  }

  /**
   * 获取购物车总价
   */
  getTotal() {
    return this.total
  }

  /**
   * 获取指定商品在购物车中的数量
   * @param {string} productId 商品ID
   */
  getItemQuantity(productId) {
    const item = this.items.find(item => item.id === productId)
    return item ? item.quantity : 0
  }

  /**
   * 检查商品是否在购物车中
   * @param {string} productId 商品ID
   */
  hasItem(productId) {
    return this.items.some(item => item.id === productId)
  }

  /**
   * 更新购物车统计信息
   */
  updateTotals() {
    this.count = this.items.reduce((sum, item) => sum + item.quantity, 0)
    this.total = this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    
    // 保留两位小数
    this.total = Math.round(this.total * 100) / 100
  }

  /**
   * 获取购物车摘要信息
   */
  getSummary() {
    return {
      items: this.items.length,
      count: this.count,
      total: this.total,
      isEmpty: this.items.length === 0
    }
  }

  /**
   * 验证购物车商品库存
   * @param {Array} stockList 库存列表
   */
  validateStock(stockList) {
    const invalidItems = []
    
    this.items.forEach(item => {
      const stock = stockList.find(s => s.id === item.id)
      if (!stock || !stock.available || stock.quantity < item.quantity) {
        invalidItems.push({
          ...item,
          stockQuantity: stock ? stock.quantity : 0,
          available: stock ? stock.available : false
        })
      }
    })
    
    return invalidItems
  }

  /**
   * 应用优惠券
   * @param {Object} coupon 优惠券信息
   */
  applyCoupon(coupon) {
    if (!coupon || !coupon.discount) {
      return this.total
    }

    let discountAmount = 0
    
    switch (coupon.type) {
      case 'percentage':
        discountAmount = this.total * (coupon.discount / 100)
        break
      case 'fixed':
        discountAmount = Math.min(coupon.discount, this.total)
        break
      case 'shipping':
        // 运费券暂不处理
        break
    }

    // 应用最小消费限制
    if (coupon.minAmount && this.total < coupon.minAmount) {
      return this.total
    }

    // 应用最大优惠限制
    if (coupon.maxDiscount) {
      discountAmount = Math.min(discountAmount, coupon.maxDiscount)
    }

    return Math.max(0, this.total - discountAmount)
  }

  /**
   * 获取商品分类统计
   */
  getCategoryStats() {
    const stats = {}
    
    this.items.forEach(item => {
      const category = item.category || '其他'
      if (!stats[category]) {
        stats[category] = {
          count: 0,
          quantity: 0,
          total: 0
        }
      }
      
      stats[category].count += 1
      stats[category].quantity += item.quantity
      stats[category].total += item.price * item.quantity
    })
    
    return stats
  }
}

// 创建购物车实例
const cart = new Cart()

// 便捷方法
export const cartUtils = {
  // 添加商品
  add: (product, quantity) => cart.addItem(product, quantity),
  
  // 移除商品
  remove: (productId) => cart.removeItem(productId),
  
  // 更新数量
  updateQuantity: (productId, quantity) => cart.updateQuantity(productId, quantity),
  
  // 增加数量
  increase: (productId) => cart.increaseQuantity(productId),
  
  // 减少数量
  decrease: (productId) => cart.decreaseQuantity(productId),
  
  // 清空购物车
  clear: () => cart.clear(),
  
  // 获取商品列表
  getItems: () => cart.getItems(),
  
  // 获取总数量
  getCount: () => cart.getCount(),
  
  // 获取总价
  getTotal: () => cart.getTotal(),
  
  // 获取商品数量
  getItemQuantity: (productId) => cart.getItemQuantity(productId),
  
  // 检查是否包含商品
  hasItem: (productId) => cart.hasItem(productId),
  
  // 获取摘要
  getSummary: () => cart.getSummary(),
  
  // 验证库存
  validateStock: (stockList) => cart.validateStock(stockList),
  
  // 应用优惠券
  applyCoupon: (coupon) => cart.applyCoupon(coupon),
  
  // 获取分类统计
  getCategoryStats: () => cart.getCategoryStats()
}

export default cart 